package bookmanagementsystem.gui;

import bookmanagementsystem.dao.BookDAO;
import bookmanagementsystem.dao.BorrowingDAO;
import bookmanagementsystem.dao.ReturningDAO;
import bookmanagementsystem.model.Book;
import bookmanagementsystem.model.BorrowingRecord;
import bookmanagementsystem.model.ReturningRecord;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.util.List;

public class MainFrame extends JFrame {
    private JLabel welcomeLabel;
    // 保留用于图书查询、借阅、归还功能相关的组件
    private JTextField bookIDField;
    private JTextField bookNameField;
    private JTextField authorNameField;
    private JTextField quantityInLibraryField;
    private JTextField locationField;
    private JButton queryBookButton;
    private JButton borrowBookButton;
    private JButton returnBookButton;
    private JButton modifyPasswordButton;
    private JButton modifyPersonalInfoButton;
    private JButton queryBorrowingRecordsButton;
    private JButton queryReturningRecordsButton;
    private JList<String> bookList;
    private DefaultListModel<String> listModel;
    // 用于存储当前登录用户的ID（假设在登录成功后已经获取并传递到这里，实际应用中需要根据具体情况设置）
    private String currentUserID;

    // 创建DAO对象，方便后续使用，避免在各个方法中重复创建
    private BookDAO bookDAO;
    private BorrowingDAO borrowingDAO;
    private ReturningDAO returningDAO;

    public MainFrame() {
        setTitle("图书管理系统 - 主界面");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 初始化DAO对象
        bookDAO = new BookDAO();
        borrowingDAO = new BorrowingDAO();
        returningDAO = new ReturningDAO();

        initComponents();
        addComponentsToFrame();
        addActionListeners();
    }

    private void initComponents() {
        welcomeLabel = new JLabel("欢迎来到图书管理系统主界面！");
        bookIDField = new JTextField(20);
        bookNameField = new JTextField(20);
        authorNameField = new JTextField(20);
        quantityInLibraryField = new JTextField(20);
        locationField = new JTextField(20);
        queryBookButton = new JButton("查询图书");
        borrowBookButton = new JButton("借阅图书");
        returnBookButton = new JButton("归还图书");
        modifyPasswordButton = new JButton("修改密码");
        modifyPersonalInfoButton = new JButton("修改个人信息");
        queryBorrowingRecordsButton = new JButton("查询借书记录");
        queryReturningRecordsButton = new JButton("查询还书记录");

        listModel = new DefaultListModel<>();
        bookList = new JList<>(listModel);

        currentUserID = "示例用户ID";
    }

    private void addComponentsToFrame() {
        JPanel panel = new JPanel(new FlowLayout());

        panel.add(welcomeLabel);
        panel.add(new JLabel("图书ID："));
        panel.add(bookIDField);
        panel.add(new JLabel("图书名称："));
        panel.add(bookNameField);
        panel.add(new JLabel("作者："));
        panel.add(authorNameField);
        panel.add(new JLabel("库存数量："));
        panel.add(quantityInLibraryField);
        panel.add(new JLabel("存放位置："));
        panel.add(locationField);
        panel.add(queryBookButton);
        panel.add(borrowBookButton);
        panel.add(returnBookButton);
        panel.add(modifyPasswordButton);
        panel.add(modifyPersonalInfoButton);
        panel.add(queryBorrowingRecordsButton);
        panel.add(queryReturningRecordsButton);

        panel.add(new JLabel("图书列表："));
        panel.add(new JScrollPane(bookList));

        getContentPane().add(panel);
    }

    private void addActionListeners() {
        queryBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText();
                Book book = bookDAO.queryBookById(bookID);
                if (book!= null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "查询到图书信息如下：\n图书ID：" + book.getBookID() + "\n图书名称：" + book.getBookName() + "\n作者：" + book.getAuthorName() + "\n入库时间：" + book.getEntryTime() + "\n库存数量：" + book.getQuantityInLibrary() + "\n存放位置：" + book.getLocation());
                } else {
                    JOptionPane.showMessageDialog(MainFrame.this, "未查询到该图书信息，请检查输入的图书ID是否正确。");
                }
            }
        });

        borrowBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText();
                BorrowingRecord borrowingRecord = borrowingDAO.queryBorrowingByUserAndBook(currentUserID, bookID);
                if (borrowingRecord!= null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "您已经借阅过此图书，无需再次借阅。");
                    return;
                }

                Book book = bookDAO.queryBookById(bookID);
                if (book == null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "未查询到该图书ID对应的图书，请检查输入的图书ID是否正确。");
                    return;
                }
                if (book.getQuantityInLibrary() <= 0) {
                    JOptionPane.showMessageDialog(MainFrame.this, "该图书库存为零，无法借阅。");
                    return;
                }

                // 创建借阅记录，设置借阅时间和预计归还时间（这里假设借阅期限为30天）
                Timestamp borrowingTime = new Timestamp(System.currentTimeMillis());
                Timestamp expectedReturnTime = new Timestamp(System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L);
                BorrowingRecord newBorrowingRecord = new BorrowingRecord(currentUserID, bookID, borrowingTime, expectedReturnTime);

                // 添加借阅记录到数据库
                if (borrowingDAO.addBorrowing(newBorrowingRecord)) {
                    // 更新图书库存数量
                    if (borrowingDAO.updateBookQuantityOnBorrow(bookID)) {
                        JOptionPane.showMessageDialog(MainFrame.this, "借阅图书成功！");
                        updateBookList();
                    } else {
                        JOptionPane.showMessageDialog(MainFrame.this, "借阅图书成功，但更新图书库存数量失败，请联系管理员，错误信息：更新库存操作未成功。");
                    }
                } else {
                    JOptionPane.showMessageDialog(MainFrame.this, "借阅图书失败，请检查输入信息或联系管理员，错误信息：添加借阅记录到数据库失败。");
                }
            }
        });

        returnBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String bookID = bookIDField.getText();
                BorrowingRecord borrowingRecord = borrowingDAO.queryBorrowingByUserAndBook(currentUserID, bookID);
                if (borrowingRecord == null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "您未借阅过此图书，无法归还。");
                    return;
                }

                Timestamp returningTime = new Timestamp(System.currentTimeMillis());
                ReturningRecord returningRecord = new ReturningRecord(currentUserID, bookID, returningTime);

                // 添加归还记录到数据库
                if (returningDAO.addReturning(returningRecord)) {
                    // 更新图书库存数量
                    if (borrowingDAO.updateBookQuantityOnReturn(bookID)) {
                        JOptionPane.showMessageDialog(MainFrame.this, "归还图书成功！");
                        updateBookList();
                    } else {
                        JOptionPane.showMessageDialog(MainFrame.this, "归还图书成功，但更新图书库存数量失败，请联系管理员，错误信息：更新库存操作未成功。");
                    }
                } else {
                    JOptionPane.showMessageDialog(MainFrame.this, "归还图书失败，请检查输入信息或联系管理员，错误信息：添加归还记录到数据库失败。");
                }
            }
        });

        modifyPasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ModifyUserInfoFrame modifyUserInfoFrame = new ModifyUserInfoFrame(currentUserID);
                modifyUserInfoFrame.setVisible(true);
            }
        });

        modifyPersonalInfoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ModifyPersonalInfoFrame modifyPersonalInfoFrame = new ModifyPersonalInfoFrame(currentUserID);
                modifyPersonalInfoFrame.setVisible(true);
            }
        });

        queryBorrowingRecordsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List<BorrowingRecord> borrowingRecords = borrowingDAO.queryBorrowingRecordsByUser(currentUserID);
                if (borrowingRecords.isEmpty()) {
                    JOptionPane.showMessageDialog(MainFrame.this, "您暂无借书记录。");
                } else {
                    StringBuilder message = new StringBuilder("您的借书记录如下：\n");
                    for (BorrowingRecord record : borrowingRecords) {
                        message.append("借书记录ID：").append(record.getRecordID()).append("\n");
                        message.append("图书ID：").append(record.getBookID()).append("\n");
                        message.append("借阅时间：").append(record.getBorrowingTime()).append("\n\n");
                    }
                    JOptionPane.showMessageDialog(MainFrame.this, message.toString());
                }
            }
        });

        queryReturningRecordsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List<ReturningRecord> returningRecords = returningDAO.queryReturningRecordsByUser(currentUserID);
                if (returningRecords.isEmpty()) {
                    JOptionPane.showMessageDialog(MainFrame.this, "您暂无还书记录。");
                } else {
                    StringBuilder message = new StringBuilder("您的还书记录如下：\n");
                    for (ReturningRecord record : returningRecords) {
                        message.append("还书记录ID：").append(record.getRecordID()).append("\n");
                        message.append("图书ID：").append(record.getBookID()).append("\n");
                        message.append("归还时间：").append(record.getReturningTime()).append("\n\n");
                    }
                    JOptionPane.showMessageDialog(MainFrame.this, message.toString());
                }
            }
        });

        updateBookList();
    }

    private void updateBookList() {
        listModel.clear();
        for (Book book : bookDAO.queryAllBooks()) {
            listModel.addElement(book.getBookID() + " - " + book.getBookName());
        }
    }
}